package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.admin.jwt.AppJwtUtil;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.AdUserService;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.common.BCrypt;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service
public class AdUserServiceImpl extends BaseServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        //判断用户或者账号密码是否为空
        if (dto == null || StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword()))return errorParam;
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        //根据登录用户名查询看看是否有此用户
        if (adUser ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //如果有，获取登录传过来的密码进行MD5加密
        String tbPwd = adUser.getPassword();
        String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + adUser.getSalt()).getBytes());
        //判断传过来的密码加密后跟数据库存储的密码是否相同
        if (tbPwd.equals(pwd)){
            Map<String,Object> map = new HashMap<>();
            //jwt一键生成token
            String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
            //返回时将密码跟盐值设置为空，以防被抓包获取
            adUser.setSalt("");
            adUser.setPassword("");
            adUser.setLoginTime(new Date());
            map.put("token",token);
            map.put("user",adUser);
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"请输入正确密码");
    }

    @Override
    public ResponseResult register(AdUser adUser) {
        if (adUser == null)return errorParam;
        AdUser one = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUser.getName()));
        if (one !=null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"用户已存在");
        }
        String salt = RandomStringUtils.randomAlphanumeric(5);
        adUser.setSalt(salt);
        adUser.setPassword(BCrypt.hashpw(adUser.getPassword(),BCrypt.gensalt()));
        adUser.setCreatedTime(new Date());
        save(adUser);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
